<template>

  <div class="head-container">
    <el-input v-model="deptName" class="mb-20px" clearable placeholder="请输入部门名称">
      <template #prefix>
        <Icon icon="ep:search" />
      </template>
    </el-input>
  </div>
   <div class="head-container">
  <el-tree
    ref="treeRef"
    :data="treeData"
    :props="{
      label: 'name',
      children: 'children'
    }"
    :check-strictly="checkStrictly"
    node-key="id"
    :default-expand-all="isExpand"
    :filter-node-method="filterNode"
    show-checkbox
    :default-checked-keys="checkedKeys"
    @check="handleCheck"
  />
   </div>
</template>

<script lang="ts" setup>
import * as DeptApi from '@/api/system/dept'
import { handleTree } from '@/utils/tree'
// 接受外部传递的参数
const props = defineProps({
  isExpand: {
    type: Boolean,
    default: false
  },
  checkStrictly: {
    type: Boolean,
    default: false
  }
})

// 事件传递给父组件：返回勾选的节点
const emit = defineEmits(['update:checkedKeys'])
const treeRef = ref(null)
const treeData = ref<any[]>([])
const checkedKeys = ref<string[]>([])
const deptName = ref('')
/** 查询树数据 */
const getTreeData = async () => {
  const cacheKey = 'regionTreeData' // 缓存的键名

  // 检查 localStorage 是否有缓存
  const cachedData = localStorage.getItem(cacheKey)
  if (cachedData) {
    treeData.value = JSON.parse(cachedData)
    return
  }

  try {
    const data = await DeptApi.getDeptRole()
    const tree = handleTree(data)
    treeData.value = tree

    // 缓存树数据到 localStorage
    localStorage.setItem(cacheKey, JSON.stringify(tree))
  } finally {
  }
}
/** 基于名字过滤 */
const filterNode = (name: string, data: Tree) => {
  if (!name) return true
  return data.name.includes(name)
}
// 调用接口获取数据
onMounted(() => {
  getTreeData()
})
/** 监听deptName */
watch(deptName, (val) => {
  treeRef.value!.filter(val)
})
const handleCheck = () => {
  const checked = treeRef.value?.getCheckedKeys() || []
  checkedKeys.value = checked
  emit('update:checkedKeys', checked)
}
</script>

<style scoped>
</style>
